/* eslint-disable radix */

/* eslint-disable no-undef */
/* eslint-disable react-native/no-inline-styles */

import AntDesign from 'react-native-vector-icons/AntDesign';
import Entypo from 'react-native-vector-icons/Entypo';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import {useSelector} from 'react-redux';
import {update} from '@/utils/request';
import React, {useState, useEffect, memo} from 'react';
import {
  View,
  Text,
  Colors,
  Avatar,
  Button,
  TouchableOpacity,
  Slider,
  Dialog,
  PanningProvider,
  Constants,
} from 'react-native-ui-lib';
import {difftimes} from '@/utils/time';
import dayjs from 'dayjs';
import Input from '../Input';
import {DeviceEventEmitter, useWindowDimensions} from 'react-native';

const items = {
  0: {
    value: 0,
    statusName: '未开始',
    key: 'undo',
    bg: 'undoBg',
    icon: <Entypo name="google-play" size={16} color={Colors.undo} />,
  },
  1: {
    value: 1,
    statusName: '进行中',
    key: 'doingBg',
    bg: 'doingBg',
    icon: <AntDesign name="ellipsis1" color={Colors.white} />,
  },
  2: {
    value: 2,
    statusName: '已完成',
    key: 'doneBg',
    bg: 'doneBg',

    icon: <AntDesign name="check" size={16} color={Colors.done} />,
  },
};

const Action = ({item, refreshAsync, head = false, selectedDate}) => {
  const {width} = useWindowDimensions();

  const currentUser = useSelector(state => state.userInfo);
  const isMine = currentUser?.id === item.userId;

  const Prefix = global.file;

  const [modal, setModal] = useState({
    open: false,
  });

  const [progress, setProgress] = useState(item?.progress ?? 0);

  const [time, setTime] = useState(0);
  const [workDate, setWorkDate] = useState(dayjs());

  useEffect(() => {
    if (!selectedDate) {
      return;
    }
    if (dayjs(selectedDate).valueOf() > dayjs().valueOf()) {
      setWorkDate(dayjs());
    } else {
      setWorkDate(dayjs(selectedDate));
    }
  }, [selectedDate]);

  let inputprops = {
    placeholder: '工时',
    value: time,
    lefticon: 'clockcircleo',
    allowClear: true,
    onChange: val => {
      setTime(val);
    },
    size: 'small',
    keyboardType: 'numeric',
  };

  const Report = (
    <View>
      {item.status === 1 && (
        <View spread row centerV marginB-12>
          <Text subheading>进度</Text>
          <Text body>{progress}%</Text>
        </View>
      )}

      {item.status === 1 && (
        <Slider
          minimumValue={0}
          maximumValue={100}
          minimumTrackTintColor={Colors.primaryColor}
          thumbTintColor={Colors.primaryColor}
          value={progress}
          onValueChange={val => {
            setProgress(parseInt(val));
          }}
        />
      )}
      <View
        spread
        row
        centerV
        style={{marginTop: item.status !== 1 ? 0 : 12, marginBottom: 12}}>
        <Text subheading>工时</Text>
        <Text center body>
          {time}h
        </Text>
      </View>
      <View row center>
        <Input {...inputprops} />
      </View>
    </View>
  );

  const [state, setState] = useState({});

  const doNext = async key => {
    setProgress(item?.progress);
    if (key === 'progress') {
      setState({
        title: item.status === 1 ? '输入任务进度/工时' : '输入任务工时',
        type: 'bottom',
        visible: true,
      });
      return;
    }

    if (key === 'bug') {
      setModal(s => ({
        ...s,
        open: true,
        type: 'bug',
        title: '添加BUG任务',
      }));
      return;
    }
    if (item?.status === 2 || item?.status === 3) {
      return;
    }
    if (item?.status === 0) {
      await update('/item/' + item?.id, {
        status: 1,
      });
      refreshAsync();
    } else if (item?.status === 1) {
      await update('/item/' + item?.id, {
        status: 2,
      });
      refreshAsync();
    }
  };

  // const [open, setOpen] = useState(false);

  // const {runAsync} = useRequest(
  //   async () => {
  //     let res = await get('/user', {projectId: item?.projectId});
  //     return res?.data?.dataList ?? [];
  //   },
  //   {
  //     debounceWait: 200,
  //     manual: true,
  //     refreshDeps: [open],
  //   },
  // );

  return (
    <View
      spread
      flex-1
      row
      centerV
      marginT-10
      onPress={e => {
        e.stopPropagation();
      }}>
      <Dialog
        {...state}
        renderPannableHeader={() => (
          <View>
            <View margin-18>
              <Text heading>{state.title}</Text>
            </View>
          </View>
        )}
        onDismiss={() => {
          setState({
            visible: false,
          });
        }}
        pannableHeaderProps={state}
        panDirection={PanningProvider.Directions.DOWN}
        bottom={true}
        width={width - 24}
        // overlayBackgroundColor={'transparent'}
        containerStyle={{
          backgroundColor: Colors.colorCardBg,
          marginBottom: 12,
          borderRadius: 12,
        }}>
        <View padding-18 paddingT-0>
          {Report}
          <View marginT-18 right>
            <Button
              label="提交"
              size="small"
              style={{
                borderRadius: 6,
                width: 40,
                backgroundColor: Colors.primaryColor,
              }}
              onPress={async () => {
                setState(s => ({
                  ...s,
                  visible: false,
                }));
                await update('/item/' + item?.id, {
                  progress,
                  time,
                  workDate: workDate.format('YYYY-MM-DD'),
                });
                await refreshAsync();

                DeviceEventEmitter.emit('toast', {
                  message: '填写成功！',
                  type: 'success',
                });
                setProgress(0);
                setTime(0);
              }}
            />
          </View>
        </View>
      </Dialog>

      <View flex-1 left row centerV style={{gap: 8}}>
        {head === false ? null : (
          <TouchableOpacity
            style={{
              flexDirection: 'row',
              justifyContent: 'center',
              alignItems: 'center',
              gap: 6,
            }}
            onPress={async e => {
              // e.stopPropagation();
              // await runAsync();
            }}>
            <Avatar
              source={{
                uri: Prefix + item?.userHeadUrl,
              }}
              size={30}
              label={item?.userHeadUrl ? null : item?.userName?.charAt(0)}
            />
            <Text body>{item?.userName}</Text>
          </TouchableOpacity>
        )}
        <View row center style={{gap: 8}}>
          <Text
            style={{
              color: Colors[items[item?.status]?.key],
              fontWeight: 'bold',
            }}>
            {items[item?.status]?.statusName}
          </Text>

          {!item?.planEnd ? null : (
            <View row center>
              {difftimes(
                dayjs(dayjs(item?.planEnd).format('YYYY-MM-DD') + ' 18:00:00'),
                dayjs(),
                item?.status,
                'format1',
              )}
            </View>
          )}
        </View>
      </View>

      <View
        center
        style={{gap: 10}}
        row
        onPress={e => {
          e.stopPropagation();
        }}>
        {item?.status !== 0 && (
          <Button
            style={{
              width: 30,
              height: 30,
              padding: 0,
            }}
            center
            round
            onPress={() => {
              doNext('progress');
            }}
            backgroundColor={Colors.green60}>
            <AntDesign name="clockcircle" size={16} color={Colors?.green10} />
          </Button>
        )}

        {isMine && item?.status === 2 && (
          <Button
            style={{
              width: 30,
              height: 30,
              padding: 0,
            }}
            center
            round
            onPress={() => {
              doNext('bug');
            }}
            backgroundColor={Colors.$backgroundDangerLight}>
            <FontAwesome name={'bug'} size={18} color={Colors.$iconDanger} />
          </Button>
        )}

        {isMine && item?.status !== 2 && (
          <Button
            style={{
              width: 30,
              height: 30,
              padding: 0,
            }}
            center
            round
            onPress={item.status !== 2 ? doNext : () => {}}
            backgroundColor={Colors[items[item?.status]?.bg]}>
            {items[item?.status]?.icon}
          </Button>
        )}
      </View>
    </View>
  );
};

export default memo(Action);
